package com.forgenet.testclient.panel;

import com.forgenet.message.PacketId;
import com.forgenet.message.base.req.ReqGateLoginPacket;
import com.forgenet.testclient.ClientMain;
import com.sparrow.common.util.HttpUtil;
import com.sparrow.common.util.JsonUtil;
import com.sparrow.common.util.PropertiesUtil;
import com.sparrow.socket.http.bean.HttpResponse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class CreateRolePanel extends JPanel implements ActionListener {

    private final JTextField usernameField;
    private final JTextField nameField;
    private final JButton registerButton;

    public CreateRolePanel() {
        setLayout(new GridBagLayout());
        int row = 0;

        add(new JLabel("账号:"), createGBC(0, row));
        usernameField = new JTextField(20);
        add(usernameField, createGBC(1, row++));

        add(new JLabel("角色名字:"), createGBC(0, row));
        nameField = new JTextField(20);
        add(nameField, createGBC(1, row++));

        registerButton = new JButton("创建角色");
        registerButton.addActionListener(this);
        add(registerButton, createGBC(1, row));
    }

    private GridBagConstraints createGBC(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String username = usernameField.getText().trim();
        String roleName = new String(nameField.getText()).trim();

        if (username.isEmpty() || roleName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            String url = PropertiesUtil.getProperty("login.url");
            Integer packetId = PacketId.LoginServer.REQ_CREATE_ACCOUNT;
            url = url + String.format("?packetId=%d&userName=%s&roleName=%s", packetId, username, roleName);
            HttpUtil.getAsync(url, null, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException ex) {
                    ex.printStackTrace();
                    SwingUtilities.invokeLater(() ->
                            JOptionPane.showMessageDialog(CreateRolePanel.this, "无法连接服务器", "错误", JOptionPane.ERROR_MESSAGE)
                    );
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String jsonString = response.body().string();
                        HttpResponse httpResponse = JsonUtil.parse(jsonString, HttpResponse.class);
                        int code = httpResponse.getCode();
                        SwingUtilities.invokeLater(() -> {
                            if (code == 0) {
                                JOptionPane.showMessageDialog(CreateRolePanel.this, "账号已存在", "注册失败", JOptionPane.ERROR_MESSAGE);
                            } else if (code == 1) {
                                handleResp(httpResponse, username, roleName);
                            } else {
                                JOptionPane.showMessageDialog(CreateRolePanel.this, "注册失败，请重试", "注册失败", JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void handleResp(HttpResponse httpResponse, String username, String roleName) {
        System.out.println("登录服创建分配成功 " + JsonUtil.toJSON(httpResponse));
        String gateIp = (String) httpResponse.getResults().get("gate-ip");
        Integer gatePort = (Integer) httpResponse.getResults().get("gate-port");
        String token = (String) httpResponse.getResults().get("token");
        ClientMain.connect("gate", gateIp, gatePort);
        //登录网关
        ReqGateLoginPacket reqGateLoginPacket = new ReqGateLoginPacket();
        reqGateLoginPacket.setToken(token);
        reqGateLoginPacket.setCreateRole(true);
        ClientMain.channel.writeAndFlush(reqGateLoginPacket);

        //
        ClientMain.cache.put("account", username);
        ClientMain.cache.put("roleName", roleName);
    }

}
